from random import randint
from celery_tasks.meiduofunc.tasks import send_template_sms
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView
from django.conf import settings
from rest_framework_jwt.settings import api_settings
from carts.utils import merge_cart_cookie_to_redis
from meiduo_hmh.utils import contones
from .serializers import QQCreateSerializer, WeiboCreateSerializer
from oauth.models import oauthQQUser, OAuthSinaUser
from QQLoginTool.QQtool import OAuthQQ
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from meiduo_hmh.utils.weibo import WeiboAPIClient

# Create your views here.

class OauthQQCodeView(APIView):
    def get(self, request):
        data = request.query_params
        state = data.get('next')
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state=state)
        qq_url = qq.get_qq_url()

        return Response({'login_url': qq_url})


class OauthQQOpenidView(CreateAPIView):
    serializer_class = QQCreateSerializer

    def get(self, request):

        code = request.query_params.get('code')
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state='/')
        access_token = qq.get_access_token(code)
        openid = qq.get_open_id(access_token)

        try:
            qq_user = oauthQQUser.objects.get(openid=openid)
        except:
            tjs = TJS(settings.SECRET_KEY, 300)
            data = tjs.dumps(openid).decode()

            return Response({'access_token': data})
        else:
            # data = { }
            # data['user_id'] = qq_user.user.id
            # data['username'] = qq_user.user.username
            user = qq_user.user

            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            # payload = jwt_payload_handler(qq_user) # JWT 回传的数据必须要有username
            payload = jwt_payload_handler(user)

            token = jwt_encode_handler(payload)
            # data['token'] = token

            # return Response(data)
            response = Response({'token': token, 'username': user.username, 'user_id': user.id})

            response = merge_cart_cookie_to_redis(request, response, user)

            return response


class OauthWeiboCodeView(APIView):

    def get(self,request):

        weibo = WeiboAPIClient(app_key="3305669385",app_secret="74c7bea69d5fc64f5c3b80c802325276",redirect_uri="http://www.meiduo.site:8080/sina_callback.html")
        weibo_url = weibo.get_authorize_url()

        return Response({'login_url':weibo_url})

class OauthWeibotokenView(CreateAPIView):

    serializer_class = WeiboCreateSerializer

    def get(self,request):
        data = request.query_params
        code = data.get('code')
        # return Response({'access_token':code}) #-------测试用--------
        weibo = WeiboAPIClient(app_key="3305669385", app_secret="74c7bea69d5fc64f5c3b80c802325276",redirect_uri="http://www.meiduo.site:8080/sina_callback.html")
        try:
            token = weibo.request_access_token(code=code)
        except:
            return Response(status=500)
        access_token = token.get('access_token')
        try:
            weibo_client = OAuthSinaUser.objects.get(access_token=access_token)
        except:

            tjs = TJS(settings.SECRET_KEY,300)
            data = tjs.dumps(access_token).decode()

            return Response({'access_token':data})
        else:
            user = weibo_client.user

            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            # payload = jwt_payload_handler(qq_user) # JWT 回传的数据必须要有username
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            response = Response({'user_id':user.id,'username':user.username,'token':token})

            response = merge_cart_cookie_to_redis(request,response,user)

            return response

class OauthWeiboSmscodeView(APIView):

    def get(self,request,mobile):

        conn_sms = get_redis_connection('sms_code')
        if conn_sms.get('sms_code_flag:%s' % mobile):
            return Response({'message': '短信发送过于频繁'}, status=status.HTTP_400_BAD_REQUEST)

        data = request.query_params
        image_code = data.get('text')
        image_code_id = data.get('image_code_id')
        conn = get_redis_connection('image_code')
        redis_image_code = conn.get('image_code:%s'%image_code_id)
        if not redis_image_code:
            return Response('验证码已失效!',status=400)
        if redis_image_code.decode().lower() != image_code.lower():
            return Response('验证码不正确',status=400)

        sms_code = '%06d' % randint(0, 999999)
        print(sms_code)
        # conn = get_redis_connection('sms_code')
        pl = conn_sms.pipeline()
        pl.setex('sms_code:%s' % mobile, contones.conton_sms_code_time, sms_code)
        pl.setex('sms_code_flag:%s' % mobile, contones.conton_sms_code_flag_time, '1')
        pl.execute()
        # ccp = CCP()
        # ccp.send_template_sms(mobiel,[sms_code,'5'],1)
        send_template_sms.delay(mobile, sms_code)

        return Response({'message': 'ok'})

